import { setStorage, getStorage } from '../../bridge.js'
import { normalApp } from '../index.js'

export const name = '系统设置'

const { Input, Modal, Form, Switch, Select } = window.antd

const { Option } = Select
const h = window.React.createElement

const appList = Object.keys(normalApp).map((key) => ({
  key,
  name: normalApp[key].name,
}))

const getSearchUrl = (type, s) => {
  if (type === 'baidu') {
    return `https://www.baidu.com/s?wd=${s}`
  } else if (type === 'bing') {
    return `https://cn.bing.com/search?q=${s}`
  } else if (type === 'google') {
    return `https://www.google.com/search?q=${s}`
  }
}

class System extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      showDialog: false,
      showSearchDialog: false,
      searchType: 'baidu',
      appConfigMap: Object.keys(normalApp).reduce((result, key) => {
        result[key] = true
        return result
      }, {}),
    }
    this.form = React.createRef()
    this.searchInput = React.createRef()
    this.searchForm = React.createRef()

    this.loadAppConfigMap()
    this.loadSearchData()
  }

  componentDidMount() {
    window.$eventbus.on('appKeydown', (ev) => {
      if (ev.data === 'Enter') {
        this.setState(
          {
            showSearchDialog: true,
          },
          () => {
            setTimeout(() => {
              this.searchInput.current.focus()
            })
          }
        )
      }
    })
  }

  async loadAppConfigMap() {
    const appConfigMap = await getStorage('appConfigMap')
    if (appConfigMap) {
      this.setState({
        appConfigMap,
      })
    }
  }

  async loadSearchData() {
    const searchData = await getStorage('searchData')
    if (searchData) {
      this.setState({
        searchType: searchData.type || 'baidu',
      })
    }
  }

  onFinish = (values) => {
    const { appConfigMap: oldAppConfigMap } = this.state
    this.setState({
      appConfigMap: values,
    })
    setStorage('appConfigMap', values)
    // 对比更改后的值，通知全局变更
    Object.keys(values)
      .filter((key) => values[key] !== oldAppConfigMap[key])
      .forEach((key) => {
        window.$eventbus.emit('appUpdate', {
          key,
          enabled: values[key],
        })
      })
  }

  onSearchFinish = (values) => {
    const { keyword } = values
    if (!keyword) {
      return
    }
    if (this.searchForm.current) {
      this.searchForm.current.resetFields()
    }
    const { searchType } = this.state
    const searchUrl = getSearchUrl(searchType, keyword)
    window.open(searchUrl)
  }

  onSearchTypeChange = (value) => {
    this.setState({
      searchType: value,
    })
    setStorage('searchData', { type: value })
  }

  render() {
    const { showDialog, appConfigMap, showSearchDialog, searchType } =
      this.state
    return h(
      'div',
      {
        className: 'flex-center',
        style: { borderRight: 'solid 1px #eee' },
      },
      h('i', {
        className: 'workdial wd-setting pointer',
        onClick: () => this.setState({ showDialog: true }),
      }),
      h(
        Modal,
        {
          title: '模块开关',
          open: showDialog,
          width: 400,
          okText: '保存',
          cancelText: '取消',
          onCancel: () => this.setState({ showDialog: false }),
          onOk: async () => {
            const valid = await this.form.current.validateFields()
            if (valid) {
              this.form.current.submit()
              this.setState({
                showDialog: false,
              })
            }
          },
        },
        h(
          Form,
          {
            ref: this.form,
            name: 'basic',
            initialValues: {
              ...appConfigMap,
            },
            onFinish: this.onFinish,
            autoComplete: 'off',
          },
          appList.map((p) =>
            h(
              Form.Item,
              {
                key: p.key,
                name: p.key,
                label: p.name,
                valuePropName: 'checked',
              },
              h(Switch)
            )
          )
        )
      ),
      h(
        Modal,
        {
          open: showSearchDialog,
          width: 800,
          closable: false,
          footer: null,
          bodyStyle: { padding: 12 },
          onCancel: () => this.setState({ showSearchDialog: false }),
        },
        h(
          Form,
          {
            ref: this.searchForm,
            name: 'basic',
            initialValues: {
              type: searchType,
              keyword: '',
            },
            onFinish: this.onSearchFinish,
            autoComplete: 'off',
          },
          h(
            Form.Item,
            {
              style: { marginBottom: 0 },
            },
            h(
              Input.Group,
              {
                style: { display: 'flex' },
                compact: true,
              },
              h(
                Form.Item,
                {
                  name: 'type',
                  noStyle: true,
                },
                h(
                  Select,
                  { style: { width: 100 }, onChange: this.onSearchTypeChange },
                  h(Option, { value: 'baidu' }, '百度'),
                  h(Option, { value: 'bing' }, '必应'),
                  h(Option, { value: 'google' }, 'Google')
                )
              ),
              h(
                Form.Item,
                {
                  name: 'keyword',
                  noStyle: true,
                },
                h(Input, {
                  ref: this.searchInput,
                  style: { flex: 1 },
                  onPressEnter: () => {
                    this.searchForm.current.submit()
                  },
                  placeholder: '输入关键字搜索',
                })
              )
            )
          )
        )
      )
    )
  }
}

let app
export const render = ({ root }) => {
  app = ReactDOM.createRoot(root)
  app.render(h(System, null))
}

export const unmount = () => {
  app && app.unmount()
}
